package com.lxw.framework.utils;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.Date;

public class DateUtils {
    /**
     * 按照分钟向前
     *
     * @param sub
     * @return
     */
    public static LocalDateTime getMinusNow(Long sub) {
        return LocalDateTime.now().minusMinutes(sub);
    }

    /**
     * 按照小时向前
     *
     * @param sub
     * @return
     */
    public static LocalDateTime getHour(Long sub) {
        return LocalDateTime.now().minusHours(sub);
    }

    /**
     * 日期字符串转日期
     *
     * @param dateStr
     * @param pattern
     * @return
     */
    public static LocalDateTime dateStrToDate(String dateStr, String pattern) {
        DateTimeFormatter df = DateTimeFormatter.ofPattern(pattern);
        LocalDateTime ldt = LocalDateTime.parse(dateStr, df);
        return ldt;
    }

    /*
     * 获取指定时间的指定格式-例如"yyyy-MM-dd HH:mm:ss"等
     */
    public static String formatTime(LocalDateTime time, String pattern) {
        return time.format(DateTimeFormatter.ofPattern(pattern));
    }

    /**
     * 获取今天时间的指定格式
     *
     * @param pattern
     * @return
     */
    public static String formatNow(String pattern) {
        return formatTime(LocalDateTime.now(), pattern);
    }

    /**
     * 获取月初
     * @param time
     * @return
     */
    public static String getMonthFirst(LocalDateTime time){
        return formatTime(time,"yyyy-MM-01 00:00:00");
    }
    /**
     * 获取月末
     * @param time
     * @return
     */
    public static String getMonthEnd(LocalDateTime time){
        Integer month = time.getMonthValue()+1;
        String dt = formatTime(time,"yyyy-"+month+"-01 00:00:00");
        time = LocalDateTime.parse(dt,DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
        time = time.minusSeconds(1L);
        return formatTime(time,"yyyy-MM-dd HH:mm:ss");
    }

    /**
     * Date转LocalDate
     * @param date
     * @return
     */
    public static LocalDateTime dateTolocalDateTime(Date date) {
        Instant instant = date.toInstant();
        ZoneId zone = ZoneId.systemDefault();
        LocalDateTime localDateTime = LocalDateTime.ofInstant(instant, zone);
        return localDateTime;
    }
}
